package com.hand.wfive.loginAndVip.ui

import android.content.Context
import android.content.Intent
import android.view.View
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.activity.PrivacyActivity
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.MD5Util
import com.hand.wfive.loginAndVip.MobileLogin
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.model.MobileLoginCheckModel
import com.hand.wfive.util.click.NoFastClickUtils
import com.netease.nis.quicklogin.listener.QuickLoginTokenListener
import com.qmuiteam.qmui.widget.QMUITopBarLayout
import com.rxjava.rxlife.RxLife
import com.sdk.Unicorn.base.module.manager.SDKManager
import kotlinx.android.synthetic.main.login_activity_login_index.*
import org.jetbrains.anko.startActivity
import rxhttp.wrapper.param.RxHttp
import java.util.*

class LoginIndexActivity : LoginBaseActivity() {

    companion object {
        @JvmStatic
        fun show(context: Context?, isBuy: Boolean = false) {
            if (MobileLogin.getInstance().mobileLoginModel != null &&
                MobileLogin.getInstance().mobileLoginModel.mobile.isNotEmpty()
            ) {
                context?.startActivity<LoginIndexActivity>(LoginConfig.paramsIsBuy to isBuy)
            } else {
                context?.startActivity<LoginPasswordActivity>(LoginConfig.paramsIsBuy to isBuy)
            }
        }
    }

    private var mMobileStatus = 0

    override fun getContentViewId() = R.layout.login_activity_login_index

    override fun init() {
        initLogin()
        tvWelcome.text = "欢迎登录${getString(R.string.app_name)}"

        // 本机号码一键登录
        MobileLogin.getInstance().prefetchLive.observe(this) {
            if (it == null) return@observe
            mMobileStatus = if (it.isPrefetchResult) 1 else 2
        }
        MobileLogin.getInstance().initQuickLogin()

        tvMobile.text = MobileLogin.getInstance().mobileLoginModel.mobile
    }

    fun loginIndexBtnClick(v: View) {
        if (NoFastClickUtils.isFastClick()) return
        when (v) {
            login_huawei -> /*华为账号登录*/ huaweiLogin()
            login_wechat -> /*微信一键登录*/ wechatLogin()
            login_mobile -> /*本机号码一键登录*/ mobileLoginCheck()
            /*login_other -> *//*其他登录方式*//* {
                val intent = Intent(mContext, LoginCodeActivity::class.java)
                intent.putExtra(LoginConfig.paramsIsBuy, mIsBuy)
                mOtherLogin.launch(intent)
            }*/
            login_password -> {
                val intent = Intent(mContext, LoginPasswordActivity::class.java)
                intent.putExtra(LoginConfig.paramsIsBuy, mIsBuy)
                mOtherLogin.launch(intent)
            }
            login_privacy_policy -> /*隐私政策*/ {
                PrivacyActivity.showRule(mContext, PrivacyActivity.ShowPolicy)
            }
            login_user_agreement -> /*用户协议*/ {
                PrivacyActivity.showRule(mContext, PrivacyActivity.ShowUserAgreement)
            }
            login_policy -> /* 勾选隐私政策和用户协议 */ {
                login_policy_agree.isSelected = !login_policy_agree.isSelected
                if (login_policy_agree.isSelected) {
                    login_policy_agree.setImageResource(R.mipmap.login_checkbox_sel)
                } else {
                    login_policy_agree.setImageResource(R.mipmap.login_checkbox_nor)
                }
            }
        }
    }

    override fun getTopBar(): QMUITopBarLayout = topBar

    override fun loginSuccess() {
        MobileLogin.getInstance().clearScripCache()
    }

    /**** 本机号码一键登录 start ****/
    private fun mobileLoginCheck() {
        if (!login_policy_agree.isSelected) {
            showNormalTip(topBar, "请阅读并同意隐私政策和用户协议")
            return
        }
        when (mMobileStatus) {
            0 -> showNormalTip(topBar, "正在获取本机号码, 请稍后")
            1 -> {
                showLoading("正在登录")
                mobileLogin()
            }
            2 -> {
                showNormalTip(topBar, MobileLogin.getInstance().mobileLoginModel
                    .msg.ifEmpty { "获取本机号码失败\n请检查移动数据是否开启" })
                clearMobileLoginCache()
            }
        }
    }

    private fun mobileLogin() {
        MobileLogin.getInstance().onePass(object : QuickLoginTokenListener() {
            /*
            * 获取运营商token成功
            * @param YDToken    易盾token
            * @param accessCode 运营商accessCode
            */
            override fun onGetTokenSuccess(YDToken: String, accessCode: String) {
                println("MobileLogin: onGetTokenSuccess: $YDToken, $accessCode")
                MobileLogin.getInstance().quitActivity()
                SDKManager.releaseConnect(App.getContext())
                getRealPhone(YDToken, accessCode)
            }

            /*
             * 获取运营商token失败
             * @param YDToken 易盾token
             * @param msg     出错提示信息
             */
            override fun onGetTokenError(YDToken: String, msg: String) {
                println("MobileLogin: onGetTokenError: $YDToken, $msg")
                hideLoading()
                MobileLogin.getInstance().quitActivity()
                showNormalTip(topBar, msg.ifEmpty { "登陆失败" })
                clearMobileLoginCache()

            }

            override fun onCancelGetToken() {
                hideLoading()
                showNormalTip(topBar, "取消本机号码一键登录")
            }
        })
    }

    private fun clearMobileLoginCache() {
        mMobileStatus = 0
        SDKManager.releaseConnect(App.getContext())
        MobileLogin.getInstance().clearScripCache()
        MobileLogin.getInstance().initQuickLogin()
    }

    private fun getRealPhone(YDToken: String, accessCode: String) {
        val params = HashMap<String, String>()
        params["token"] = YDToken
        params["accessToken"] = accessCode
        params["secretId"] = LoginConfig.MobileSecretId
        params["businessId"] = LoginConfig.MobileBusinessId
        params["version"] = "v1"
        params["timestamp"] = "${System.currentTimeMillis()}"
        params["nonce"] = UUID.randomUUID().toString().replace("-", "")
        RxHttp.postForm("https://ye.dun.163.com/v1/oneclick/check").addAll(params)
            .add("signature", MD5Util.genSignature(LoginConfig.MobileSecretKey, params))
            .asClass(MobileLoginCheckModel::class.java)
            .to(RxLife.toMain(this))
            .subscribe({
                if (it.code == ApiConfig.SUCCESSCODE) {
                    val mobile = it.data.phone
                    register(mobile, mobile, mobile, UserManager.LoginType_mobile)
                } else {
                    hideLoading()
                    clearMobileLoginCache()
                    println("${it.code}, ${it.msg}")
                    showNormalTip(topBar, "登录失败，请重试")
                }
            }, {
                hideLoading()
                showNormalTip(topBar, "网络异常，请重试！")
            })
    }
    /**** 本机号码一键登录 end ****/


}
